package safe.yunchexing.com.cloudsafe.utils;

import android.util.Base64;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 安全
 */
public class SecurityUtil {

    private static final String KEY_SHA = "SHA-1";
    private final static String HEX = "0123456789abcdef";
    private final static int BASE64_FLAG = Base64.DEFAULT;

    private SecurityUtil() {

    }

    public static String encryptSha(String input) {
        if (input == null) {
            return null;
        }
        String ciphertext = null;
        try {
            MessageDigest sha1 = MessageDigest.getInstance(KEY_SHA);
            try {
                sha1.update(input.getBytes("ISO-8859-1"));
            } catch (UnsupportedEncodingException e) {
            }
            byte[] ciphertextBytes = sha1.digest();
            ciphertext = toHex(ciphertextBytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return ciphertext;
    }

    public static String toHex(byte[] buf) {
        if (buf == null)
            return "";
        StringBuffer result = new StringBuffer(2 * buf.length);
        for (int i = 0; i < buf.length; i++) {
            appendHex(result, buf[i]);
        }
        return result.toString();
    }

    private static void appendHex(StringBuffer sb, byte b) {
        sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
    }

    //String to String
    public static String encodeToBase64String(String plaintext) {
        return Base64.encodeToString(plaintext.getBytes(), BASE64_FLAG);
    }

    public static String decodeFromBase64String(String ciphertext) {
        return new String(Base64.decode(ciphertext, BASE64_FLAG));
    }

    // String to byte[]
    public static byte[] encodeToBase64Bytes(String plaintext) {
        return Base64.encode(plaintext.getBytes(), BASE64_FLAG);
    }

    public static String decodeFromBase64Bytes(byte[] ciphertext) {
        return new String(Base64.decode(ciphertext, BASE64_FLAG));
    }
}
